#include "Actor.h"

NS_GM_BEGIN

Actor::Actor()
:m_body(NULL),m_ptmRatio(0)
{

}


Actor::~Actor()
{

}

bool Actor::init()
{

	return Sprite::init();
}

void Actor::syncPhysicsTransform()
{
	b2Vec2 pos = m_body->GetPosition();

	float x = pos.x * m_ptmRatio;
	float y = pos.y * m_ptmRatio;

	if (_ignoreAnchorPointForPosition)
	{
		x += _anchorPointInPoints.x;
		y += _anchorPointInPoints.y;
	}

	// Make matrix
	float radians = m_body->GetAngle();
	float c = cosf(radians);
	float s = sinf(radians);

	if (!_anchorPointInPoints.isZero())
	{
		x += ((c * -_anchorPointInPoints.x * _scaleX) + (-s * -_anchorPointInPoints.y * _scaleY));
		y += ((s * -_anchorPointInPoints.x * _scaleX) + (c * -_anchorPointInPoints.y * _scaleY));
	}

	// Rot, Translate Matrix

	float mat[] = { (float)c * _scaleX, (float)s * _scaleX, 0, 0,
		(float)-s * _scaleY, (float)c * _scaleY, 0, 0,
		0, 0, 1, 0,
		x, y, 0, 1 };

	_transform.set(mat);
}



float Actor::getPTMRatio() const
{
	return m_ptmRatio;
}

void Actor::setPTMRatio(float fRatio)
{
	m_ptmRatio = fRatio;
}

//
// Common to Box2d and Chipmunk
//

const Vec2& Actor::getPosFromPhysics() const
{
	static Vec2 s_physicPosion;

	b2Vec2 pos = m_body->GetPosition();
	float x = pos.x * m_ptmRatio;
	float y = pos.y * m_ptmRatio;
	s_physicPosion.set(x, y);

	return s_physicPosion;
}

void Actor::setPosition(float x, float y)
{
	float angle = m_body->GetAngle();
	m_body->SetTransform(b2Vec2(x / m_ptmRatio, y / m_ptmRatio), angle);
}

void Actor::setPosition(const Vec2 &pos)
{
	setPosition(pos.x, pos.y);
}

void Actor::setPositionX(float x)
{
	setPosition(x, getPositionY());
}

void Actor::setPositionY(float y)
{
	setPosition(getPositionX(), y);
}

float Actor::getRotation() const
{
	return CC_RADIANS_TO_DEGREES(m_body->GetAngle());
}

void Actor::setRotation(float fRotation)
{
	b2Vec2 p = m_body->GetPosition();
	float radians = CC_DEGREES_TO_RADIANS(fRotation);
	m_body->SetTransform(p, radians);

}

// Override the setters and getters to always reflect the body's properties.
const Vec2& Actor::getPosition() const
{
	return getPosFromPhysics();
}

void Actor::getPosition(float* x, float* y) const
{
	if (x == nullptr || y == nullptr) {
		return;
	}
	const Vec2& pos = getPosFromPhysics();
	*x = pos.x;
	*y = pos.y;
}

float Actor::getPositionX() const
{
	return getPosFromPhysics().x;
}

float Actor::getPositionY() const
{
	return getPosFromPhysics().y;
}
NS_GM_END